import { useEffect, useState } from 'react'
import { GetProps, InputNumber } from 'antd'
import type { ICellRendererParams } from '@ag-grid-community/core'

import styles from './styles.module.less'

type TInputNumberProps = GetProps<typeof InputNumber>

interface IInputNumberCellRendererProps extends ICellRendererParams<any, number | string> {
  inputNumberProps?: Omit<TInputNumberProps, 'value' | 'onChange'>
}

export const InputNumberCellRenderer = Object.assign(
  ({ value, node, column, colDef, data, inputNumberProps }: IInputNumberCellRendererProps) => {
    const [localValue, setLocalValue] = useState<any>(value as any)

    // 外部值变化时，同步到本地显示
    useEffect(() => {
      setLocalValue(value as any)
    }, [value])

    // 计算是否可编辑（用于禁用控制），兼容 editable 为布尔或函数
    const isEditable = (() => {
      const editable = colDef?.editable as any
      try {
        if (typeof editable === 'function') {
          return !!editable({ data, node, colDef })
        }
        return !!editable
      } catch {
        return !!editable
      }
    })()

    return (
      <InputNumber
        {...inputNumberProps}
        className={styles.InputNumberCellRenderer}
        disabled={!isEditable}
        value={localValue as any}
        onChange={val => {
          setLocalValue(val as any)
        }}
        onBlur={() => {
          // 失焦时再提交到 grid 数据，避免输入中失焦
          const colId =
            column?.getColId?.() ?? (typeof (column as any)?.colId === 'string' ? (column as any).colId : undefined)
          if (colId && node) {
            node.setDataValue(colId, localValue as any)
          }
        }}
      />
    )
  },
  {
    defineProps: (
      props: Pick<IInputNumberCellRendererProps, 'inputNumberProps'>,
    ): Pick<IInputNumberCellRendererProps, 'inputNumberProps'> => props,
  },
)
